package com.candy.security.jwt.handle;

import com.candy.common.result.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler
{

	@Resource
	private ObjectMapper objectMapper;

	@Override
	public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException
	{
		// 返回了验证失败的状态码401，并把异常信息以Json返回
		//int value = HttpStatus.UNAUTHORIZED.value();
		//resp.setStatus(value);
		String errorMessage = e.getMessage();
		if(errorMessage==null || errorMessage.equalsIgnoreCase("Bad credentials"))
		{
			errorMessage = "认证失败";
		}
		R jsonData = new R(HttpStatus.UNAUTHORIZED, errorMessage);
		resp.setContentType("application/json;charset=utf-8");
		PrintWriter out = resp.getWriter();
		out.write(objectMapper.writeValueAsString(jsonData));
		out.flush();
		out.close();
	}
}